import { ref, watch, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import type { Router } from 'vue-router';

export function useRouteStack(router: Router) {
	const route = useRoute();
	const isBack = ref(false); // 是否为回退操作
	const routeStack = ref<string[]>([]); // 路由历史栈

	// 初始化路由栈（从sessionStorage读取或初始化）
	const initRouteStack = () => {
		const savedStack = sessionStorage.getItem('routeStack');
		routeStack.value = savedStack ? JSON.parse(savedStack) : [];
		// 若当前路由不在栈中（如直接访问链接），添加初始路径
		if (!routeStack.value.includes(route.fullPath)) {
			routeStack.value.push(route.fullPath);
			sessionStorage.setItem('routeStack', JSON.stringify(routeStack.value));
		}
	};

	// 更新路由栈（全局路由守卫）
	const setupRouterGuard = () => {
		router.beforeResolve((to) => {
			const newPath = to.fullPath;
			// 避免重复添加相同路径
			if (routeStack.value[routeStack.value.length - 1] !== newPath) {
				routeStack.value.push(newPath);
				sessionStorage.setItem('routeStack', JSON.stringify(routeStack.value));
			}
			return true;
		});
	};

	// 检测回退操作
	const checkBackNavigation = () => {
		const currentPath = route.fullPath;
		const currentIndex = routeStack.value.indexOf(currentPath);
		// 若当前路径在栈中且不是最后一项 → 回退触发
		if (currentIndex > -1 && currentIndex < routeStack.value.length - 1) {
			isBack.value = true;
			// 截断后续无效路径
			routeStack.value = routeStack.value.slice(0, currentIndex + 1);
			sessionStorage.setItem('routeStack', JSON.stringify(routeStack.value));
		} else {
			isBack.value = false;
		}
	};

	// 手动重置路由栈（如退出登录时调用）
	const resetRouteStack = () => {
		routeStack.value = [];
		sessionStorage.removeItem('routeStack');
	};

	// 初始化逻辑
	onMounted(() => {
		initRouteStack();
		setupRouterGuard();
	});

	// 监听路由变化
	watch(
		() => route.fullPath,
		() => {
			checkBackNavigation();
		}
	);

	return { isBack, routeStack, resetRouteStack };
}
